<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Nikkei;
use App\Services\NikkeiService;
use Cache;

class CheckNikkeiData
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($this->shouldGetNikkei()) {
            $date = now()->subDay()->toDateString();
            $service = new NikkeiService();
            $datas = $service->getNikkeiData($date);

            if(!$datas) {
                return response()->json(['error' => 'failed to get nikkei data'], 400);
            }
            Cache::set('nikkei_date', now()->toDateString());
        }
        
        return $next($request);
    }


    private function shouldGetNikkei() {
        $date = Cache::get('nikkei_date');
        if(!$date) {
            return true;
        }
        return now()->toDateString() != $date;
    }
}
